import { EggLogger } from 'egg';
import { Inject, HTTPController, HTTPMethod, HTTPMethodEnum, Context, EggContext, Middleware, HTTPBody, HTTPQuery } from '@eggjs/tegg';
import { responseFormatter } from 'app/middleware/responseFormatter';
import { AddProcessOptions, UpdateProcessOptions } from 'typings/app/process';
import { EggAppConfig } from 'typings/app';
import { group } from 'radash';
// import { toInt, removeUndefinedValues } from 'app/libs/utils';

@HTTPController({
  path: '/process',
})
@Middleware(responseFormatter)
export class ProcessController {
  @Inject()
  logger: EggLogger;
  @Inject()
  config: EggAppConfig;

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/updateProcess',
  })
  async updateProcess(@Context() ctx: EggContext, @HTTPBody() process: UpdateProcessOptions) {
    await ctx.model.Process.update(process, {
      where: { id: process.id },
    });
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.DELETE,
    path: '/deleteProcess',
  })
  async deleteProcess(@Context() ctx: EggContext, @HTTPQuery() id: number) {
    const process = await ctx.model.Process.findByPk(id);
    await process.destroy();
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/addProcess',
  })
  async addProcess(@Context() ctx: EggContext, @HTTPBody() process: AddProcessOptions) {
    const currProcess = await ctx.model.Process.findOne({
      where: { name: process.name, workshop_id: process.workshopId },
    });
    if (currProcess) {
      ctx.throw({
        code: 1001,
        message: '添加失败，当前工厂存在同名的车间！',
      });
    }
    await ctx.model.Process.create(process);
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getProcessOptions',
  })
  async getProcessOptions(@Context() ctx: EggContext) {
    const sql = `SELECT a.id, a.name, b.name as workshopName, b.id as workshopId,
    c.name as factoryName, c.id as factoryId
    FROM bordsys_process_test as a
    LEFT JOIN bordsys_workshop_test as b ON a.workshop_id = b.id
    LEFT JOIN bordsys_factory_test as c ON b.factory_id = c.id ORDER BY b.factory_id, a.workshop_id;`;
    const [ list, , ] = await ctx.model.query(sql);
    return group(list, (item: any) => item.factoryId);
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getProcessList',
  })
  async getProcessList(@Context() ctx: EggContext) {
    const [ list, total ] = await ctx.model.query(`SELECT a.*, b.name as workshopName, c.name as factoryName
    FROM bordsys_process_test as a
    LEFT JOIN bordsys_workshop_test as b ON a.workshop_id = b.id
    LEFT JOIN bordsys_factory_test as c ON b.factory_id = c.id ORDER BY b.factory_id, a.workshop_id;`);
    return { list, total };
  }
}
